package live.zhuangsen.brevo.controller;

import jakarta.servlet.http.HttpServletRequest;
import live.zhuangsen.brevo.vo.FriendlyCaptchaVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;

/**
 * @author madison
 * {@code @description}
 * {@code @date} 2023/11/5 16:54
 */

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("api")
public class IndexController {
    private static final Logger logger = LoggerFactory.getLogger(IndexController.class);

    @Value("${friendly-captcha.siteverify-api}")
    private String siteverifyApi;

    @Value("${friendly-captcha.api-key}")
    private String apiKey;

    @Value("${friendly-captcha.site-key}")
    private String siteKey;

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("canary")
    public String canary() {
        return "v2";
    }

    @PostMapping("brevo")
    public String brevo(HttpServletRequest request) {
//        Enumeration<String> attributeNames = request.getAttributeNames();
//        while (attributeNames.hasMoreElements()) {
//            String name = attributeNames.nextElement();
//            Object attribute = request.getAttribute(name);
//            logger.info("attr name:{}, value:{}", name, attribute);
//        }

        Map<String, String[]> parameterMap = request.getParameterMap();
        parameterMap.forEach((key, value) -> {
            String[] strings = parameterMap.get(key);
            for (String val : strings) {
                logger.info("key:{}, val:{}", key, val);
            }
        });
        try {
            StringBuilder buffer = new StringBuilder();
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            String requestBody = buffer.toString();
            logger.info("requestBody:{}", requestBody);
        } catch (IOException e) {
            logger.error("get json data:", e);
        }
        return "brevo";
    }

    @PostMapping("captcha")
    public String captcha(@RequestBody FriendlyCaptchaVo friendlyCaptcha) {
        logger.info("friendlyCaptcha:{}", friendlyCaptcha);
        friendlyCaptcha.setSitekey(siteKey);
        friendlyCaptcha.setSecret(apiKey);
        logger.info("friendlyCaptcha:{}", friendlyCaptcha);
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(siteverifyApi, friendlyCaptcha, String.class);
        logger.info(stringResponseEntity.getBody());
        return "captcha";
    }
}
